import os

class GMT():
    
    cmdstack = []
    minmax = [None, None, None, None]
    title = ''
    mapwidth = 15
    legend = []
    scalelength = 10
    
    def __init__(self):
        pass
        
    def plots(self, data, **args):
        '''Plots the sites on the map
        '''
        pdict = {'fcolor':'red', 'size':'0.15'}
        for key in args:            
            if key in pdict:  pdict[key] = args[key]
        
        if 'title' in args:
            self.legend.append([args['title'],'s',pdict['fcolor'], pdict['size']])            
        # finding min and max and compare it with a global minmax
        minmax = os.popen ("minmax -C %s" % (data))
        minmax = minmax.readlines(); 
        minmax = [float(x) for x in minmax[0][:-1].split('\t')]
        
        if minmax[0] < self.minmax[0] or self.minmax[0] == None: self.minmax[0] = minmax[0]
        if minmax[1] > self.minmax[1] or self.minmax[1] == None: self.minmax[1] = minmax[1]
        if minmax[2] < self.minmax[2] or self.minmax[2] == None: self.minmax[2] = minmax[2]
        if minmax[3] > self.minmax[3] or self.minmax[3] == None: self.minmax[3] = minmax[3]
        
        self.cmdstack.append('cat %s | psxy -R -J -Sc%s -G%s' % (data, pdict['size'], pdict['fcolor']))
        
    def plotl(self, data, **args):
        '''Plots the lines on the map        
        '''
        pdict = {'lcolor':'black', 'size':'thin'}
        for key in args:            
            if key in pdict:  pdict[key] = args[key]
        
        if 'title' in args:
            self.legend.append([args['title'],'l',pdict['lcolor'], pdict['size']])
        
        # finding min and max and compare it with a global minmax
        minmax = os.popen ("minmax -M -C %s" % (data))
        minmax = minmax.readlines(); 
        minmax = [float(x) for x in minmax[0][:-1].split('\t')]
        
        if minmax[0] < self.minmax[0] or self.minmax[0] == None: self.minmax[0] = minmax[0]
        if minmax[1] > self.minmax[1] or self.minmax[1] == None: self.minmax[1] = minmax[1]
        if minmax[2] < self.minmax[2] or self.minmax[2] == None: self.minmax[2] = minmax[2]
        if minmax[3] > self.minmax[3] or self.minmax[3] == None: self.minmax[3] = minmax[3]
        
        self.cmdstack.append('cat %s | psxy -M -R -J -W%s/%s' % (data, pdict['size'], pdict['lcolor']))
        
    def plota(self, data, **args):
        '''Plots the areas on the map
        '''
        pdict = {'fcolor':'gray', 'size':'thin'}
        for key in args:            
            if key in pdict:  pdict[key] = args[key]
        
        if 'title' in args:
            self.legend.append([args['title'],'a',pdict['fcolor'], pdict['size']])
        
        # finding min and max and compare it with a global minmax
        minmax = os.popen ("minmax -M -C %s" % (data))
        minmax = minmax.readlines(); 
        minmax = [float(x) for x in minmax[0][:-1].split('\t')]
        
        if minmax[0] < self.minmax[0] or self.minmax[0] == None: self.minmax[0] = minmax[0]
        if minmax[1] > self.minmax[1] or self.minmax[1] == None: self.minmax[1] = minmax[1]
        if minmax[2] < self.minmax[2] or self.minmax[2] == None: self.minmax[2] = minmax[2]
        if minmax[3] > self.minmax[3] or self.minmax[3] == None: self.minmax[3] = minmax[3]
        
        self.cmdstack.append('cat %s | psxy -M -L -R -J -G%s' % (data, pdict['fcolor']))
        
    
    def hcopy(self, filename, **args):
        for key in args:            
            if hasattr(self, key):
                setattr(self,key,args[key])
        self.find_region_boundary()   
        
        os.system("gmtset BASEMAP_TYPE plain")
        
        os.system("echo 'pscoast -R%s/%s/%s/%s -JM%s -K -Dl -A120 -Wthinnest > %s' > %s.sh" % \
        (self.minmax[0],self.minmax[1],self.minmax[2],self.minmax[3], self.mapwidth, filename, filename))
        for cmd in self.cmdstack:
            os.system("echo '%s -K -O >> %s' >> %s.sh" % (cmd, filename, filename))
        
        if self.legend == []:
            os.system("echo 'psbasemap -R -J -O -B%sg%s:.\"%s\": >> %s' >>%s.sh" \
                             % (self.long_step, self.lat_step, self.title, filename, filename))
        else:
            os.system("echo 'psbasemap -R -J -O -K -B%sg%s:.\"%s\": -L%s/%s/%s/%s/%s >> %s' >>%s.sh" \
                               % (self.long_step, self.lat_step, self.title, self.minmax[0], self.minmax[2], self.minmax[0], self.minmax[2], self.scalelength, filename, filename))
            self.plot_legend(filename)
        
        os.system('sh %s.sh' % filename)
            
    
    def find_region_boundary(self):
        minmax = self.minmax
        
        steps = [360, 180, 90, 30, 10, 5, 2, 1, 0.5, 0.16, 0.083, 0.016]
        
        self.long_step = minmax[1] - minmax[0]
        self.lat_step   = minmax[3] - minmax[2]
        
        # finding min from a list that bigger than long_step, lat_step
        self.long_step = [x for x in steps if x<self.long_step][0]
        self.lat_step = [x for x in steps if x<self.lat_step][0]

        # finding the Region boundries
        self.minmax[0] = minmax[0] - minmax[0] % self.long_step
        self.minmax[1] = minmax[1] - minmax[1] % self.long_step + self.long_step
        self.minmax[2] = minmax[2] - minmax[2] % self.lat_step
        self.minmax[3] = minmax[3] - minmax[3] % self.lat_step + self.lat_step       
    
    def plot_legend(self, fname):
        os.system("echo 'pslegend -R0/10/0/10 -JX20 -L2.4 -D10.5/0/5/14/BL -O <<EOF>> %s' >> %s.sh" % (fname, fname))
        for item in self.legend:
            if item[1]=='s':
                title = item[0]
                color = item[2]
                size = item[3]
                os.system("echo 'S 0.5 c %s %s - 1.2 %s' >> %s.sh" % (size, color, title, fname))
            if item[1]=='l':
                title = item[0]
                color = item[2]
                size = item[3]
                os.system("echo 'S 0.5 - 1 - %s,%s 1.2 %s' >> %s.sh" % (size, color, title, fname))
            if item[1]=='a':
                title = item[0]
                color = item[2]
                size = item[3]
                os.system("echo 'S 0.5 s 1 %s %s 1.2 %s' >> %s.sh" % (color, size, title, fname))
        os.system("echo 'EOF' >> %s.sh" % fname)
